﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using EventsTest.Models;
using Newtonsoft.Json;

namespace EventsTest.Controllers
{
    public class EventSourceApiController : ApiController
	{
		static ConcurrentDictionary<int, StreamWriter> clients = new ConcurrentDictionary<int, StreamWriter>();
		static int key = 0;

		public HttpResponseMessage Get()
		{
			HttpResponseMessage response = Request.CreateResponse();
			response.Content = new PushStreamContent(OnStreamAvailable, "text/event-stream");
			return response;
		}

		public HttpResponseMessage Post(ChatMessage chat)
		{
			foreach (var clientkey in clients.Keys)
			{
				var client = clients[clientkey];
				try
				{
					client.WriteLine("data: " + JsonConvert.SerializeObject(chat) + "\n");
					client.Flush();
				}
				catch (Exception)
				{
					clients.TryRemove(clientkey, out client);
				}
			}

			return Request.CreateResponse();
		}

		public static void OnStreamAvailable(Stream stream, HttpContent headers, TransportContext context)
		{
			StreamWriter streamwriter = new StreamWriter(stream);
			clients[key] = streamwriter;
			key++;
		}
    }
}
